package cn.shopthrive.merchants;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import androidx.core.content.ContextCompat;

import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

public class WeChatHelper {
  private static final String TAG = "WeChatHelper";
  private static final String APP_ID = "wx111a6ee438a3e70e";

  private static IWXAPI api;
  private static BroadcastReceiver refreshReceiver;

  /**
   * 初始化微信 SDK 并注册 App，支持刷新广播
   */
  public static void init(Context context) {
    if (api == null) {
      api = WXAPIFactory.createWXAPI(context, APP_ID, true);
      api.registerApp(APP_ID);
    }

    if (refreshReceiver == null) {
      // 监听系统发来的 ACTION_REFRESH_WXAPP，用于重新注册 AppID
      refreshReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context ctx, Intent intent) {
          api.registerApp(APP_ID);
        }
      };
      IntentFilter filter = new IntentFilter("com.tencent.mm.plugin.openapi.Intent.ACTION_REFRESH_WXAPP");
      ContextCompat.registerReceiver(context, refreshReceiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED);
    }
  }

  /**
   * 检查微信是否已安装
   */
  public static boolean isWeChatInstalled() {
    return api != null && api.isWXAppInstalled();
  }

  /**
   * 发起微信登录授权请求
   */
  public static boolean login() {
    if (api == null) {
      return false;
    }
    SendAuth.Req req = new SendAuth.Req();
    req.scope = "snsapi_userinfo";
    req.state = "wechat_sdk_login_state";
    boolean sent = api.sendReq(req);
    return sent;
  }

  /**
   * 在 WXEntryActivity 的 onCreate/onNewIntent 中调用，
   * 将接收到的 Intent 分发给 SDK 解析并触发 onReq/onResp
   */
  public static void handleIntent(Context context, Intent intent, IWXAPIEventHandler handler) {
    if (api == null) {
      api = WXAPIFactory.createWXAPI(context, APP_ID, true);
      api.registerApp(APP_ID);
    }
    api.handleIntent(intent, handler);
  }

  /**
   * 将 SDK onResp 得到的 BaseResp 通过广播转给 native‑wechat 插件
   */
  @SuppressLint("UnprotectedReceiver")
public static void broadcastResponse(Context ctx, BaseResp resp) {
    Intent i = new Intent("com.hector.nativewechat.ACTION_REDIRECT_INTENT");
    i.putExtra("errCode", resp.errCode);
    if (resp instanceof SendAuth.Resp) {
        SendAuth.Resp auth = (SendAuth.Resp) resp;
        i.putExtra("code",  auth.code);
        i.putExtra("state", auth.state);
    }
    ctx.sendBroadcast(i);
}

  /**
   * 清理注册的 BroadcastReceiver，释放资源
   */
  public static void cleanup(Context context) {
    if (refreshReceiver != null) {
      context.unregisterReceiver(refreshReceiver);
      refreshReceiver = null;
    }
    api = null;
  }
}
